package cc;

import com.jtattoo.plaf.acryl.AcrylLookAndFeel;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.border.StandardBorderPainter;
import org.jvnet.substance.button.ClassicButtonShaper;
import org.jvnet.substance.watermark.SubstanceBinaryWatermark;
import spride.SprideAllUrl;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 下载视频
 */
public class Tools {
    static Tools window = null;
    private JFrame frame;
    JPanel announcePanel = new JPanel();
    Label contentLable = new Label();
    TextField contentText = new TextField();
    Label contentLable2 = new Label();
    TextField contentText2 = new TextField();
    TextArea textArea = new TextArea();
    Button m_btnok = new Button();
    Button m_btncancle = new Button();
    static int width;
    static int height;

    /**
     * Launch the application
     *
     * @param args
     */
    public static void main(String[] args) {
        try {
            //设置外观
            UIManager.setLookAndFeel(new AcrylLookAndFeel());
            JFrame.setDefaultLookAndFeelDecorated(true);
            //设置按钮外观
            SubstanceLookAndFeel.setCurrentButtonShaper(new ClassicButtonShaper());
            //设置水印
            SubstanceLookAndFeel.setCurrentWatermark(new SubstanceBinaryWatermark());
            //设置边框
            SubstanceLookAndFeel.setCurrentBorderPainter(new StandardBorderPainter());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }


        SystemClipboardMonitor temp = new SystemClipboardMonitor();
        Tools.open();
    }

    public static void open() {
        try {
            window = new Tools();
            window.frame.setTitle("tools");
            window.frame.setResizable(false);
            window.frame.setVisible(true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create the application
     */
    public Tools() {
        initialize();
    }

    /**
     * Initialize the contents of the frame
     */
    private void initialize() {
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize();
        width = screenSize.width;
        height = screenSize.height;

        frame = new JFrame();
        frame.getContentPane().setForeground(new Color(255, 255, 255));

        frame.setBounds((width - 500) / 2, (height - 275) / 2, 500, 275);//窗口居中
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Call panel
        announcePanel.setName("Call");
        announcePanel.setLayout(null);
        frame.add(announcePanel);
        announcePanel.setBounds(500, 0, 500, 0);
        announcePanel.setBackground(new Color(250, 250, 250));

        contentLable.setText("title(css)：");
        contentLable.setFont(new Font(null, 10, 15));
        contentLable.setBounds(70, 40, 100, 50);
        announcePanel.add(contentLable);

        contentText.setText("#video > h1");
        contentText.setBounds(170, 50, 250, 30);
        announcePanel.add(contentText);

        contentLable2.setText("url(css)：");
        contentLable2.setFont(new Font(null, 10, 15));
        contentLable2.setBounds(70, 90, 100, 50);
        announcePanel.add(contentLable2);

        contentText2.setText("#player");
        contentText2.setBounds(170, 90, 250, 30);
        announcePanel.add(contentText2);

        textArea.setBounds(70, 150, 350, 70);
        textArea.append("file save path is D:/tmp");
        textArea.setEditable(false);
        announcePanel.add(textArea);

        m_btnok.setLabel("run");
        m_btnok.setBackground(new Color(176, 196, 222));
        announcePanel.add(m_btnok);
        m_btnok.setBounds(170, 220, 50, 30);

        m_btncancle.setLabel("cancle");
        m_btncancle.setBackground(new Color(176, 196, 222));
        announcePanel.add(m_btncancle);
        m_btncancle.setBounds(270, 220, 50, 30);

        JavaPhoneMouse aJavaPhoneMouse = new JavaPhoneMouse();
        m_btnok.addMouseListener(aJavaPhoneMouse);
        m_btncancle.addMouseListener(aJavaPhoneMouse);
    }

    //事件監聽
    class JavaPhoneMouse extends java.awt.event.MouseAdapter {
        public void mouseClicked(java.awt.event.MouseEvent event) {
            Object object = event.getSource();
            if (object == m_btnok) {
                String content = contentText.getText();
                String content2 = contentText2.getText();
                String url = getSysClipboardText();
                System.out.println("clipboardContent：" + url);
                if (url == null || url.trim().equals("")) {
                    JOptionPane.showMessageDialog(new JPanel(), "clipboardContent is empty");
                    return;
                }
                if (!url.startsWith("http")) {
                    JOptionPane.showMessageDialog(new JPanel(), "url is illegal");
                    return;
                }
                //获取title、sourceUrl
                Document doc = null;
                try {
                    doc = Jsoup.connect(url).userAgent(SprideAllUrl.userAgent).get();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                final String title = doc.select(content).text();
                final String sourceUrl = doc.select(content2).select("source").get(0).attr("src");
                File dir = new File("D:/tmp/");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                textArea.append("\n" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())) + "  " + title);
                textArea.append("\n" + "downloading... " + title);
                new Thread() {
                    public void run() {
                        try {
                            String res = HttpRequest.sendGet2(sourceUrl, "D:/tmp/" + title + ".mp4");
                            textArea.append("\n downloaded " + title);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    ;
                }.start();
                //
           /*     存在问题：下载的视频无法观看
           DownloadTask downloadTask = new DownloadTask(sourceUrl, "D:/tmp/" + title + ".mp4", 10);//10个线程
                try {
                    downloadTask.addDownloadTaskListener(new DownloadTaskListener() {
                        @Override
                        public void downloadCompleted() {//下载完成
                            textArea.append("\n" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))+" download completed");
                        }
                    });
                    downloadTask.startDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }*/
            }
            if (object == m_btncancle) {
                if (frame != null) {
                    frame.dispose();
                }
            }
        }
    }

    /**
     * 从剪切板获得文字。
     */
    public static String getSysClipboardText() {
        String ret = "";
        Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 获取剪切板中的内容
        Transferable clipTf = sysClip.getContents(null);

        if (clipTf != null) {
            // 检查内容是否是文本类型
            if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                try {
                    ret = (String) clipTf
                            .getTransferData(DataFlavor.stringFlavor);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return ret;
    }
}
